<template>
  <div class="page">
    <cube-form
      :model="model"
      :schema="schema"
      :immediate-validate="false"
      :options="options"
      @validate="validateHandler"
      @submit="submitHandler"
    ></cube-form>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  data() {
    return {
      validity: {},
      valid: undefined,
      model: {
        username: "",
        password: ""
      },
      schema: {
        groups: [
          {
            legend: "输入登录信息",
            fields: [
              {
                type: "input",
                modelKey: "username",
                label: "用户名",
                props: {
                  placeholder: "请输入用户名"
                },
                rules: {
                  required: true
                },
                trigger: "blur"
              },
              {
                type: "input",
                modelKey: "password",
                label: "密码",
                props: {
                  placeholder: "请输入密码"
                },
                rules: {
                  required: true
                },
                trigger: "blur"
              }
            ]
          },
          {
            fields: [
              {
                type: "submit",
                label: "Submit"
              }
            ]
          }
        ]
      },
      options: {
        scrollToInvalidField: true,
        layout: "standard" // classic fresh
      }
    };
  },
  methods: {
    async submitHandler(e) {
      //取消表单的默认提交
      e.preventDefault();
      let code = await this.$store.dispatch("login", this.model);
      if (code==200) {
        //登录成功重定向
        const path = this.$route.query.redirect || "/";
        this.$router.push(path);
      } else {
        //登录失败
        const toast = this.$createToast({
          time: 1000,
          txt: "登录失败",
          type: "error"
        });
        toast.show();
      }
    },
    validateHandler(result) {
      this.validity = result.validity;
      this.valid = result.valid;
    }
  }
};
</script>

<style scoped>
</style>
